package com.fzrskj.cloud.free.api;

import com.fzrskj.cloud.free.core.enums.PayWayEnum;
import com.fzrskj.cloud.free.core.tool.CJsonTool;
import com.fzrskj.cloud.free.core.tool.CStrTool;
import com.fzrskj.cloud.free.core.utils.CloudContextUtils;
import com.fzrskj.cloud.free.dic.utils.DicParamUtils;
import com.fzrskj.cloud.free.user.bean.UserCharge;
import com.fzrskj.cloud.free.user.utils.UserChargeUtils;
import ms.core.consts.SysErr;
import ms.core.object.CObject;
import ms.core.tool.HttpTool;
import net.sf.json.JSONObject;

import java.security.MessageDigest;
import java.util.Date;

public class ShenpayAPI extends CObject {
	
	public String sftpay(String params) {
		JSONObject json = JSONObject.fromObject(params);
		
		String amount=new java.text.DecimalFormat("#.00").format(json.get("amount"));
		amount=String.valueOf(Double.valueOf(amount));
		String userName = json.getString("uname");
		String uEmail = json.getString("email");
		int uId = json.getInt("uid");
		String ip = json.getString("Ip");
		JSONObject obj_result = new JSONObject();
		
		UserChargeUtils userChargeUtils = new UserChargeUtils();
		String itemsURL = "https://api.shengpay.com/mas/v1/timestamp?merchantNo=";
		String result = "";
		String payWay = DicParamUtils.getParamValue(PayWayEnum.SFT.getKey());
		Integer agentId = CloudContextUtils.getAgentId();
		if ("99".equals(payWay)) {
			agentId = DicParamUtils.getLastSelfPayParent(PayWayEnum.SFT.getKey(), agentId);
		}
		String MsgSenders = DicParamUtils.getParamValue("sftpayac", agentId);
		String md5key = DicParamUtils.getParamValue("sftpayackey", agentId);
		String rurl = DicParamUtils.getParamValue("weburl", agentId);
		if (CStrTool.isBlankStr(MsgSenders)||CStrTool.isBlankStr(md5key)||CStrTool.isBlankStr(rurl)) {
			obj_result.put("code", "-1");
			obj_result.put("message", "接口参数不全");
		    return obj_result.toString();
		}

		itemsURL=itemsURL + MsgSenders;
		HttpTool http = new HttpTool();
		String saykey = http.httpGet(itemsURL);

		if (saykey.indexOf("200")<0) {
			obj_result.put("code", "-1");
			obj_result.put("message", "您目前无法使用盛付通充值，请联系客服。");
		    return obj_result.toString();
		}
		http=null;
		String timestamp= CJsonTool.getStrValue(saykey, "timestamp","");
		String now=MsgSenders+ timestamp;

		String PageUrl = rurl+"/sftpay_receive"; 	// 支付成功后，浏览器显示支付结果的地址
		String NotifyUrl = rurl+"/sftpay_notify";  // 支付成功后，服务器端通知商户发货的地址,需要公网域名或ip
		String ProductName = "预付款:" + uEmail; 			// 商品名称

		PayForm form=new PayForm();
		form.setCharset("UTF-8");
		form.setMsgSender(MsgSenders);
		form.setSendTime(timestamp);
		form.setOrderNo(now);
		form.setOrderAmount(amount);
		form.setOrderTime(timestamp);
		form.setPageUrl(PageUrl);
		form.setNotifyUrl(NotifyUrl);
		form.setProductName(ProductName);
		form.setBuyerContact(uEmail);
		form.setBuyerIp(ip);
		if (json.get("orderId") != null) {//用于支付返回
			form.setExt1(json.get("orderId").toString());
		}

		if (json.get("instCode") != null) {//银行编码
			form.setPayType("PT001");
			form.setPayChannel("19");
			form.setInstCode(json.get("instCode").toString());
		}

		form.setSignType("MD5");
		form.setSignMsg("");

		// 插入充值记录
		UserCharge userCharge = new UserCharge();
		userCharge.setUserName(userName);
		userCharge.setUserId(uId);
		userCharge.setAmount(Double.valueOf(amount));
		userCharge.setBankCode("sftpay");
		userCharge.setStatus("N");
		userCharge.setOrderId(now);
		userCharge.setRegTime(new Date());
		userCharge.setFromAgentUserId(agentId);
		userChargeUtils.addUserCharge(userCharge);
		String code = userChargeUtils.getErrCode();
		userChargeUtils.dispose();

		if (!code.equals(SysErr.CODE_SUCCESS)) {
			obj_result.put("code", "-1");
			obj_result.put("message", "充值失败,无法添加充值记录。");
		    return obj_result.toString();
		}
		PayForm reform=signForm(form, md5key);
		result=CJsonTool.beanToJson(reform);
		result=CJsonTool.addNode(result, "paychannel", "sftpay");
		result=CJsonTool.addNode(result, "code", "1");
		result=CJsonTool.addNode(result, "message", "成功");
		return result;
	}

	public static PayForm signForm(PayForm form, String key) {
		String text = form.toSignString();
		String mac = sign(text, key, form.getCharset());
		form.setSignMsg(mac);
		return form;
	}

	private static String sign(String data, String key, String charset) {

		MessageDigest msgDigest = null;
		data = data + key;
		byte[] enbyte = null;
		try {
			msgDigest = MessageDigest.getInstance("MD5");
			msgDigest.update(data.getBytes(charset));
			enbyte = msgDigest.digest();
		} catch (Exception e) {

		}
		return bin2hex(enbyte);
	}

	/**
	 * 字符串转换成十六进制值
	 *
	 * @param bs
	 *            String 我们看到的要转换成十六进制的字符串
	 * @return
	 */
	public static String bin2hex(byte[] bs) {
		char[] digital = "0123456789ABCDEF".toCharArray();
		StringBuffer sb = new StringBuffer("");
		int bit;
		for (int i = 0; i < bs.length; i++) {
			bit = (bs[i] & 0x0f0) >> 4;
			sb.append(digital[bit]);
			bit = bs[i] & 0x0f;
			sb.append(digital[bit]);
		}
		return sb.toString();
	}
}
